#include "double_linklist.h"

DoubleLinkList DoubleLinkListCreate()
{
    DoubleLinkList list = (DoubleLinkList)malloc(sizeof(DoubleLinkListNode));
    list->next = NULL;
    list->prior = NULL;
    list->data = 1111;

    return list;
}

void DoubleLinkListGenerateNode(DoubleLinkList list)
{
    ElemType data = 100;
    int i = 0;

    DoubleLinkList temp  = (DoubleLinkList)malloc(sizeof(DoubleLinkListNode));
    temp->data = data;

    /*只有头结点的特殊处理，因为其没有后驱只需要修改两个方向就行*/
    if(list->next == NULL){
        temp->data = data++;
        list->next = temp;
        temp->prior = list;
    }

    while(i < 10)
    {
        DoubleLinkList node = (DoubleLinkList)malloc(sizeof(DoubleLinkListNode));
        node->data = data;

        /*设置插入节点*/
        node->next = list->next;
        list->next->prior = node; /*头节点的下一个的节点的前驱设置为Node*/

        /*设置插入处的前后节点*/
        node->prior = list;
        list->next = node;
        data++;
        i++;
    }

}

void DoubleLinkListTraverseNode(DoubleLinkList list)
{
    DoubleLinkListNode *head = list->next;
    while(head->next != NULL){
        head = head->next;
        printf("%d\n",head->data);
    }
}

void DoubleLinkListDeleteNode(DoubleLinkList list, int pos)
{
    /*1.判断删除位置是否合法*/
    /*2.获取删除位置的上一个节点*/
    /*3.删除*/
    if(pos < 0){
        printf("FAIL TO DELETE THIS NODE!");
        return ;
    }
    DoubleLinkListNode *prior= DoubleLinkListGetNode(list,pos-1);
    DoubleLinkList current = prior->next;
    prior->next = current->next;
    current->next->prior = prior;
    free(current);
}

DoubleLinkList DoubleLinkListGetNode(DoubleLinkList list, int pos)
{
    if(pos < 0){
        printf("FAIL TO GET THIS NODE!");
        return ;
    }
    DoubleLinkListNode *node= list->next;
    int count = 0;
    while(node->next != NULL && count < pos){
        node = node->next;
        count ++;
    }

    return node;
}

int DoubleLinkListGetLength(DoubleLinkList list)
{
    int count = 0;
    DoubleLinkList temp = list;
    while(temp->next != NULL){
        temp = temp->next;
        count++;
    }
    return count;
}
